package com.ruoyi.site.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.site.domain.UserSubscriptions;
import com.ruoyi.site.service.IUserSubscriptionsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;

import static com.ruoyi.common.utils.ServletUtils.getRequest;

/**
 * 用户订阅Controller
 *
 * @author chuckeytang
 * @date 2025-10-13
 */
@RestController
@RequestMapping("/site/subscriptions")
public class UserSubscriptionsController extends BaseController
{
    @Autowired
    private IUserSubscriptionsService userSubscriptionsService;

    @Autowired(required = false)
    private TokenService tokenService;

    /**
     * 查询用户订阅列表 (后台管理接口)
     */
    @PreAuthorize("@ss.hasPermi('site:subscriptions:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserSubscriptions userSubscriptions)
    {
        startPage();
        List<UserSubscriptions> list = userSubscriptionsService.selectUserSubscriptionsList(userSubscriptions);
        return getDataTable(list);
    }

    /**
     * 查询当前用户的有效订阅 (前台用户接口)
     * * 用于判断用户的会员权限
     */
    @GetMapping("/user/active")
    public AjaxResult getActiveSubscription()
    {
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            if (loginUser != null) {
                currentUserId = loginUser.getUserId(); // 假设这里的 userId 是 users 表中的 ID
            }
        } catch (Exception e) {
            return AjaxResult.error("用户未登录或会话无效");
        }

        if (currentUserId == null) {
            return AjaxResult.error("用户ID解析失败，请重新登录");
        }

        UserSubscriptions subscription = userSubscriptionsService.selectActiveSubscriptionByUserId(currentUserId);

        if (subscription == null) {
            return AjaxResult.success("用户无有效订阅", null);
        }

        return success(subscription);
    }

    /**
     * 导出用户订阅列表
     */
    @PreAuthorize("@ss.hasPermi('site:subscriptions:export')")
    @Log(title = "用户订阅", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserSubscriptions userSubscriptions)
    {
        List<UserSubscriptions> list = userSubscriptionsService.selectUserSubscriptionsList(userSubscriptions);
        ExcelUtil<UserSubscriptions> util = new ExcelUtil<UserSubscriptions>(UserSubscriptions.class);
        util.exportExcel(response, list, "用户订阅数据");
    }

    /**
     * 获取用户订阅详细信息
     */
    @PreAuthorize("@ss.hasPermi('site:subscriptions:query')")
    @GetMapping(value = "/{subscriptionId}")
    public AjaxResult getInfo(@PathVariable("subscriptionId") Long subscriptionId)
    {
        return success(userSubscriptionsService.selectUserSubscriptionsBySubscriptionId(subscriptionId));
    }

    /**
     * 新增用户订阅 (通常由订单支付成功后调用)
     */
    @PreAuthorize("@ss.hasPermi('site:subscriptions:add')")
    @Log(title = "用户订阅", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserSubscriptions userSubscriptions)
    {
        return toAjax(userSubscriptionsService.insertUserSubscriptions(userSubscriptions));
    }

    /**
     * 修改用户订阅 (用于续费、取消或状态变更)
     */
    @PreAuthorize("@ss.hasPermi('site:subscriptions:edit')")
    @Log(title = "用户订阅", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserSubscriptions userSubscriptions)
    {
        return toAjax(userSubscriptionsService.updateUserSubscriptions(userSubscriptions));
    }

    /**
     * 删除用户订阅
     */
    @PreAuthorize("@ss.hasPermi('site:subscriptions:remove')")
    @Log(title = "用户订阅", businessType = BusinessType.DELETE)
    @DeleteMapping("/{subscriptionIds}")
    public AjaxResult remove(@PathVariable Long[] subscriptionIds)
    {
        return toAjax(userSubscriptionsService.deleteUserSubscriptionsBySubscriptionIds(subscriptionIds));
    }
}